import OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';
import { getUploadImage } from '@/api';

const STATIC_DOMAIN = 'https://oss.xavvi.com';
const fileTypeMap = {
    image: '/aipod/images',
    video: '/aipod/video',
} as const;

type FileType = keyof typeof fileTypeMap;

const Upload = async (file: File, fileType: FileType): Promise<string> => {
    return new Promise(async (resolve, reject) => {
        try {
            const data = await getUploadImage({});
            let options = {
                ...data.data,
                bucket: 'xavvi',
                secure: true,
                region: 'ap-southeast-1',
            };
            const client = new OSS({
                accessKeyId: options.access_key_id,
                accessKeySecret: options.access_key_secret,
                stsToken: options.security_token,
                bucket: options.bucket,
                secure: options.secure,
                region: options.region,
                endpoint: 'oss-accelerate.aliyuncs.com',
                refreshSTSToken: async () => {
                    return {
                        accessKeyId: data.data.access_key_id,
                        accessKeySecret: data.data.access_key_secret,
                        stsToken: data.data.security_token,
                    };
                },
                refreshSTSTokenInterval: 3600 * 1000,
            });
            let pa = file.name.split('.');
            let path =
                fileTypeMap[fileType] +
                '/' +
                uuidv4() +
                '.' +
                pa[pa.length - 1];

            if (fileType === 'video') {
                const result = await client.multipartUpload(
                    path,
                    new Blob([file]),
                    {
                        parallel: 4,
                        partSize: 1024 * 1024,
                    }
                );
                resolve(STATIC_DOMAIN + result.name);
            } else if (fileType === 'image') {
                const result = await client.put(path, new Blob([file]));
                resolve(STATIC_DOMAIN + '/' + result.name);
            }
        } catch (error) {
            reject(error);
        }
    });
};

export default Upload;
